package com.sunwhite.herostore.common;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

public class MySqlSessionFacoty {

    /***
     * 私有化类默认构造器
     */
    private MySqlSessionFacoty(){
    }

    /**
     * mybatis sqlsession会话工厂
     */
    private static SqlSessionFactory sqlSessionFactory;

    /**
     * 初始化sqlSessionFactory
     */
    public static void init(){
        try {
            sqlSessionFactory= new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("MyBatisConfig.xml"));

        } catch (Exception e) {
            e.printStackTrace();
            new RuntimeException(e);
        }
    }

    /**
     * 开启mysql会话
     * @return mysql会话
     */
    public static SqlSession openSession(){
        if (sqlSessionFactory==null){
            return null;
        }
        return sqlSessionFactory.openSession(true);
    }
}
